<template>
  <div class="app-container teacher-form-container">
    <div v-if="opt != 'add'">
      <el-descriptions title="">
        <el-descriptions-item label="企业名称">
          <el-tag style="margin-top: -5px" size="medium">{{
              form.enterpriseName
            }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="企业信息" name="first">
        <el-form  :model="form" ref="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="行政区域" prop="administrativeArea" >
                <Treeselect v-model="form.administrativeArea" :options="options"  :flat="true" :show-count="true" :normalizer="normalizer"  placeholder="请选择行政区域" :disabled="readonly"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业名称" prop="enterpriseName">
                <el-input v-model="form.enterpriseName" placeholder="请输入企业名称" :disabled="readonly"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业性质" prop="enterpriseNature">
                <el-select v-model="form.enterpriseNature" placeholder="请选择企业性质" style="width:100%;"   :disabled="readonly">
                  <el-option
                    v-for="dict in dict.type.enterprise_nature"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="注册资金" prop="registeredCapital">
                <el-input v-model="form.registeredCapital" placeholder="请输入注册资金" :disabled="readonly" maxlength="30"  show-word-limit><template #append>万元</template></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业来源" prop="enterpriseSource">
                <!--                <el-input v-model="form.enterpriseSource" placeholder="请输入企业来源" :disabled="readonly" />-->
                <el-select v-model="form.enterpriseSource" placeholder="请选择企业来源" style="width: 100%;"    :disabled="readonly">
                  <el-option
                    v-for="dict in dict.type.enterprise_source"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="所属行业" prop="industry">
                <treeselect
                  v-model="form.industry"
                  :options="industryOptions"
                  :normalizer="industryNormalizer"
                  :searchable="true"
                  :clearable="true"
                  placeholder="请选择所属行业"
                  style="width: 100%"
                  :disabled="readonly"
                  @input="handleIndustryChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="详情地址" prop="enterpriseAddress">
                <el-input  v-model="form.enterpriseAddress" placeholder="请输入详情地址" :disabled="readonly" maxlength="50"  show-word-limit/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="法人代表" prop="legalRepresentative">
                <el-input v-model="form.legalRepresentative" placeholder="请输入法人代表" :disabled="readonly" maxlength="10"  show-word-limit/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="成立日期" prop="establishmentDate" >
                <el-date-picker clearable
                                style="width: 100%;"
                                v-model="form.establishmentDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择成立日期"
                                :disabled="readonly">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="税务号" prop="taxId">
                <el-input v-model="form.taxId" placeholder="请输入税务号" :disabled="readonly" maxlength="30"  show-word-limit/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="联系人" prop="contacts" >
                <el-input v-model="form.contacts" placeholder="请输入联系人"  :disabled="readonly" maxlength="10"  show-word-limit/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系电话" prop="telephone">
                <el-input v-model="form.telephone" placeholder="请输入联系电话" :disabled="readonly" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开户账号" prop="account">
                <el-input v-model="form.account" placeholder="请输入开户账号" :disabled="readonly" maxlength="30"  show-word-limit/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="开发经理" prop="developManager" >
                <el-input v-model="form.developManager" placeholder="请输入开发经理" @focus="selectOpen(1)" :disabled="readonly"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="业务经理" prop="businessManager" >
                <el-input v-model="form.businessManager" placeholder="请输入业务经理" @focus="selectOpen(2)" :disabled="readonly"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%;" :disabled="readonly">
                  <el-option
                    v-for="dict in dict.type.seas_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="开户银行" prop="accountBank" >
                <el-input v-model="form.accountBank" placeholder="请输入开户银行"  :disabled="readonly"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="创建人" prop="createId" >
                <el-input v-model="form.userName" placeholder="请输入创建人"  disabled="true" :disabled="readonly"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="创建时间" prop="creatTime" >
                <el-date-picker clearable
                                v-model="form.creationTime"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择创建时间"
                                style="width: 100%"
                                disabled="true"
                                :disabled="readonly">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item label="经营范围" prop="businessScope">
                <el-input v-model="form.businessScope" placeholder="请输入经营范围" type="textarea" :disabled="readonly" maxlength="500"  show-word-limit/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="营业执照" prop="uploadFile">
                <file-view  v-if="showSeas"  :limit="1" :type="fileType" :businessId="form.businessLicense" :businessCode="businessCode" ></file-view>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="text-align: center;margin-top: 20px">
          <el-button type="primary" @click="submitForm" v-show="opt!=='select'">保 存</el-button>
          <el-button @click="cancel" v-show="opt!=='select'" >关 闭</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="进展记录" name="progress" :disabled="opt==='add'">
        <div>
          <el-tabs v-model="recordsActiveTab" type="card" class="records-tabs" @tab-click="handleRecordsTabClick">
            <el-tab-pane label="线索记录" name="electric">
              <Records :bId="id" @change="loadList" v-if="honorShow===5 && recordsActiveTab === 'electric'"></Records>
            </el-tab-pane>
            <el-tab-pane label="公海记录" name="seas">
              <SeasRecords :bId="id" v-if="honorShow===5 && recordsActiveTab === 'seas'" :isAdd="false"></SeasRecords>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div style="text-align: center;">
          <el-button @click="cancel">关 闭</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="荣誉资质信息" name="second" v-if="opt!=='add'">
        <Honor v-if="honorShow===1"  :enterpriseId="form.electricId" :enterpriseName="form.enterpriseName" :isShow="opt">
        </Honor>
        <div style="text-align: center;">
          <el-button  @click="cancel">关 闭</el-button>
        </div>
      </el-tab-pane>
<!--      <el-tab-pane label="项目资金" name="fund">-->
<!--        <Funding v-if="honorShow === 3" :enterpriseId="form.electricId" :enterpriseName="form.enterpriseName">-->
<!--        </Funding>-->
<!--        <div style="text-align: center;">-->
<!--          <el-button  @click="cancel">关 闭</el-button>-->
<!--        </div>-->
<!--      </el-tab-pane>-->
      <el-tab-pane label="有效商机信息" name="businessinfo"  v-if="opt==='select'"  >
        <Businessinfo v-if="honorShow === 4" :enterpriseId="form.electricId" :enterpriseName="form.enterpriseName">
        </Businessinfo>
        <div style="text-align: center;">
          <el-button  @click="cancel">关 闭</el-button>
        </div>
      </el-tab-pane>
<!--      <el-tab-pane label="合同信息" name="contract"  v-if="opt==='select'"  >-->
<!--        <div style="text-align: center;">-->
<!--          <el-button type="primary" @click="cancel">关 闭</el-button>-->
<!--        </div>-->
<!--      </el-tab-pane>-->
<!--      <el-tab-pane label="交付信息" name="deliver"  v-if="opt==='select'"  >-->
<!--        <div style="text-align: center;">-->
<!--          <el-button type="primary" @click="cancel">关 闭</el-button>-->
<!--        </div>-->
<!--      </el-tab-pane>-->
      <el-tab-pane label="人员信息" name="third" v-if="opt==='select'">
        <Person v-if="honorShow===2"  :enterpriseId="form.electricId" :enterprise-name="form.enterpriseName" ref="person">
        </Person>
        <div style="text-align: center;">
          <el-button  @click="cancel">关 闭</el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
    <select-user ref="select"  :type="userType" :sign="sign" @ok="selectUser"></select-user>
  </div>
</template>
<script>
import {getElectric,updateElectric,addElectric} from '@/api/electric/electric';
import { getMaxEnterpriseNo } from "@/api/highSeas/seas";
import { listArea } from "@/api/area/area";
import FileView from "@/components/FileView/index"
import SelectUser from "../../system/role/selectUser.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Honor from "../../honor/index.vue";
import Person from "../person/index.vue";
import {addRecords,getRecords,delElectric} from '@/api/electric/electricFollow';
import Operate from "../businessinfo/operate.vue";
import {listType} from "@/api/maintype/type";
import Funding from "../../project/funding/index.vue";
import Businessinfo from "../businessinfo/index.vue";
//import Records from "../seas/records.vue";
import Records from "./records.vue";
import { getIndustryTree } from "@/api/enterprise/industry";
import SeasRecords from "../seas/seasRecords.vue";
export default {
  name: "updateEle",
  dicts: ['enterprise_nature','customer_industry','enterprise_records','telesales_type','honer_status','enterprise_source','seas_status'],
  components: {Businessinfo, Funding, Treeselect,SelectUser,FileView,Honor,Person,Records,SeasRecords },
  props: {
    opt: {
      type:  String,
      default:""
    },
    id:{
      type: String,
      default:""
    },
    index:{
      type: Number,
      default:null
    },
  },
  data() {
    var developmentManager = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('业务经理不能为空'));
      }
      return callback()
    };
    var businessManager = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('业务经理不能为空'));
      }
      return callback()
    };
    var contacts = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('联系人不能为空'));
      }
      return callback()
    };
    return {
      fileType:'0',
      userType:"1",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      industryOptions: [], // 行业树形数据
      // 显示搜索条件
      showSearch: true,
      optionsClass:null,
      zValue:0,
      // 总条数
      total: 0,
      enterpriseNo:"",
      // 企业信息表格数据
      recordsList: [],
      enterpriseinfo:'enterpriseinfo',
      businessId:new Date().getTime(),
      // 弹出层标题
      title: "",
      sign:'1',
      //只读
      readonly:false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        enterpriseId: null,
      },
      // 表单参数
      form: {
        markAs:[],
      },
      honorShow:'0',
      // 表单校验
      rules: {
        enterpriseName: [
          { required: true, message: "企业名称不能为空", trigger: "blur" }
        ],
        administrativeArea: [
          { required: true, message: "行政区域不能为空", trigger: "change" }
        ],
        enterpriseNature: [
          {required: true, message: "企业性质不能为空", trigger: "blur" }
        ],
        markAs: [
          { required: true, message: "标记不能为空", trigger: "change" }
        ],
        contacts: [
          {required: true, validator: contacts, trigger: "change" }
        ],
        telephone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" }
        ],
        developmentManager: [
          { required: true, validator: developmentManager, trigger: "change" }
        ],
        businessManager: [
          { required: true, validator: businessManager, trigger: "change"  }
        ],
        industry: [
          { required: true, message: "所属行业不能为空", trigger: "change"  }
        ],
        enterpriseAddress:[
          { required: true, message: "详情地址不能为空", trigger: "change"  }
        ],
      },
      //行政区域
      options:null,
      //复选框
      markAs:[],
      //选显卡默认选中
      activeName: 'first',
      businessCode:'seas',
      //
      show:'',
      //上传按钮隐藏
      isShow:true,
      url:'',
     showSeas:null,
     recordsActiveTab: 'electric',
    };
  },
  created() {
    this.area();
    this.listType();
    this.getMaxEnterpriseNoNo();
    this.getIndustryTree();
    if (this.opt==='add'){
      this.fileType=0;
      this.readonly=false;
      this.handleAdd()
    }
    if(this.opt==="edit"){
      this.fileType=1;
      this.readonly=false;
      this.handleUpdate(this.id)
    }
    if (this.opt==='select'){
      this.fileType=2;
      this.readonly=true;
      this.handleUpdate(this.id)
    }
  },
  //监听父组件传递的boolean值,用于关闭弹窗后，数据重新加载
  watch: {
    id: function(newValue, oldValue) {
      this.area();
      this.listType();
      if (this.opt==='select'){
        this.readonly=true;
        this.fileType=2;
        this.handleUpdate(this.id)
      }
      console.log(this.id)
      if(this.opt==="edit"){
        this.readonly=false;
        this.fileType=1;
        this.handleUpdate(this.id)
      }
    },
  },
  methods: {
    // 取消按钮
    cancel() {
      this.id='';
      this.open = false;
      this.showSeas=false;
      this.reset();
      this.$emit('change',false);
    },
    rowAdd(){
      this.recordsList.push({recordsId:new Date().getTime(),followTime:this.parseTime(new Date(),'{y}-{m}-{d} {hh}:{ss}'),followPerson:this.$store.state.user.name,annex:new Date().getTime(),sign:'1'})
    },
    //获取树节点数据
    listType(){
      listType({typeCode:'ele'}).then(res=>{
        console.log(res);
        this.optionsClass=res.data;
      })
    },
    // 获取行业树形数据
    getIndustryTree() {
      getIndustryTree().then(response => {
        if (response.code === 200) {
          this.industryOptions = response.data;
          console.log('行业数据:', this.industryOptions);
        } else {
          this.$modal.msgError(response.msg);
        }
      }).catch(error => {
        console.error('获取行业数据失败:', error);
        this.$modal.msgError('获取行业数据失败');
      });
    },
    loadList() {
      this.$emit('change', this.zValue);
    },
    // 格式化行业树形数据
    industryNormalizer(node) {
      return {
        id: node.industryId,
        label: node.name,
        children: node.children && node.children.length > 0 ? node.children : null
      };
    },
    // 处理行业选择变化
    handleIndustryChange(value) {
      if (value) {
        // 根据选择的行业ID更新industryType
        const findIndustryType = (options, targetId) => {
          for (const option of options) {
            if (option.industryId === targetId) {
              // 根据行业的层级设置industryType
              this.form.industryType = option.levelType === 1 ? "0" :
                option.levelType === 2 ? "1" : "2";
              return true;
            }
            if (option.children) {
              if (findIndustryType(option.children, targetId)) {
                return true;
              }
            }
          }
          return false;
        };

        findIndustryType(this.industryOptions, value);
      }
    },
    handleDelete(row){
      const recordsIds = row.recordsId;
      this.$modal.confirm('是否确认删除企业跟进记录？').then(function() {
        return delElectric(recordsIds);
      }).then(() => {
        for (let index = 0; index < this.recordsList.length; index++) {
          const element = this.recordsList[index];
          if(recordsIds==element.recordsId){
            this.recordsList.splice(index, 1)
            break
          }
        }
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    selectActiveName() {
      console.log("是否执行")
      this.activeName = 'first'
      this.honorShow='0';
    },
    getMaxEnterpriseNoNo(){
      getMaxEnterpriseNo().then(response => {
        if(response==""||response==null){
          this.noNew+="000"
        }else{
          this.noNew+=response
          this.enterpriseNo = response
        }
      })
    },
    area(){
      listArea({}).then(response => {
        this.options = response.data;
      });
    },
    selectUser(userId,userName,phone,position,nickName){
      if(this.show=='2'){
        this.$set(this.form, 'businessManager', nickName)
        this.$set(this.form, 'transactionId', userId)
      }else if(this.show=='1'){
        this.$set(this.form, 'developManager', nickName)
        this.$set(this.form, 'developmentId', userId)
      }else{
        this.$set(this.form, 'contacts', userName)
        this.$set(this.form, 'telephone', phone)
      }
    },
    selectOpen(type){
      this.show=type
      this.$refs.select.show();
    },
    getFile(data){
      console.log(data)
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.areaId,
        label: node.areaName,
        isDisabled: false,
        children: node.list && node.list.length > 0 ? node.list : 0

      }
    },
    /** 修改按钮操作 */
    handleUpdate(id) {
      this.reset();
      getElectric(id).then(response => {
        console.log(response.data)
         this.recordsList=response.data.list
       this.form=response.data;
        this.showSeas=true;
      });
    },
    /** 新增按钮操作 */
    handleAdd(){
    this.form={};
      this.showSeas=true;
      this.form.businessManager=this.$store.state.user.info.nickName;
      this.form.transactionId=this.$store.state.user.info.userId;
      console.log(   this.form.transactionId)
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.electricId != null) {
            updateElectric(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              if(this.$refs.person){
                this.$refs.person.getList();
              }
              this.cancel();
            });
          } else {
            //说明是新增
            addElectric(this.form).then(res => {
              this.$modal.msgSuccess("新增成功");
              if(this.$refs.person){
                this.$refs.person.getList();
              }
              this.cancel();
            });
          }
        }
      });
    },
    // 表单重置
    reset() {
      this.form = {
        electricId: null,
        enterpriseName: null,
        enterpriseSource: null,
        enterpriseAbbreviation: null,
        administrativeArea: null,
        legalRepresentative: null,
        establishmentDate: null,
        contractAmount: null,
        enterpriseLabel: null,
        registeredCapital: null,
        industry: null,
        contacts: null,
        telephone: null,
        bankName: null,
        taxId: null,
        developmentId: null,
        transactionId: null,
        developmentManager: null,
        businessManager: null,
        enterpriseAddress: null,
        businessScope: null,
        enterpriseNature: null,
        markAs: null,
        belongTo: null,
        creationTime: null,
        operateTime: null,
        operateId: null,
        departmentId: null,
        departmentName: null,
        organizationId: null,
        organizationName: null,
        delFlag: null,
        id:'',
        electricType:null  //电销类型
      };
      this.resetForm("form");
    },
    handleClick(tab, event){
      if(tab.name=='second'){
        this.honorShow=1
      }
      if(tab.name=='third'){
        this.honorShow=2
      }
      if (tab.name=='fund'){
        this.honorShow=3
      }
      if (tab.name==='businessinfo'){
        this.honorShow=4
      }
      if (tab.name==='progress'){
        this.honorShow=5
      }
    },
    handleRecordsTabClick(tab, event) {
      if (tab.name === 'seas') {
        this.honorShow = 5;
      }
    },
  }
};
</script>
<style scoped lang="scss">
::v-deep .el-table .el-table__header-wrapper .el-checkbox {
  display: none;
}
.teacher-form-container {
  overflow-y: auto;
  overflow-x: auto;
  padding: 16px;
  max-width: 100%;
  max-height: 80vh;
  box-sizing: border-box;
}
::v-deep .el-dialog__header {
  padding-top: 5px;
}

 .el-col {
   height: 55px;
 }

.records-tabs {
  margin-bottom: 20px;
}

::v-deep .records-tabs .el-tabs__header {
  margin-bottom: 15px;
}

::v-deep .records-tabs .el-tabs__nav {
  border-radius: 4px;
}

::v-deep .records-tabs .el-tabs__item {
  height: 36px;
  line-height: 36px;
  font-weight: 500;
}

::v-deep .records-tabs .el-tabs__item.is-active {
  background-color: #409EFF;
  color: white;
  border-radius: 4px;
}
</style>
